#include "Mutex.hpp"
#include <unistd.h>

using namespace MutexMudlue;

int ticket = 1000;

class ThreadData
{
public:
    ThreadData(Mutex& mutex,const std::string& n):lockp(&mutex), name(n)
    {}
    Mutex* lockp;
    std::string name;
};

void* route(void* args)
{
    ThreadData* td = static_cast<ThreadData*>(args);
    while(1)
    {
        LockGuard guard(*(td->lockp));
        if(ticket > 0)
        {
            usleep(1000);
            printf("%s sells ticket:%d\n", td->name.c_str(), ticket);
            ticket--;
        }
        else
            break;
    }
    return nullptr;
}


int main()
{
    Mutex mutex;
    pthread_t t1, t2, t3, t4;

    ThreadData* td1 = new ThreadData(mutex, "thread-1");
    pthread_create(&t1, nullptr, route, td1);
    
    ThreadData* td2 = new ThreadData(mutex, "thread-2");
    pthread_create(&t2, nullptr, route, td2);
    
    ThreadData* td3 = new ThreadData(mutex, "thread-3");
    pthread_create(&t3, nullptr, route, td3);
    
    ThreadData* td4 = new ThreadData(mutex, "thread-4");
    pthread_create(&t4, nullptr, route, td4);

    pthread_join(t1, nullptr);

    pthread_join(t2, nullptr);
    
    pthread_join(t3, nullptr);
    
    pthread_join(t4, nullptr);

    return 0;
}